import 'dart:io';
import 'dart:ui' as ui;

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:mybase/base_new/help/JJEmpty.dart';

/**
 * @title 加载图片
 * @info 优先级 ：网络图片 > assets/图片 > 沙盒图片
 * @param centerSlice 指定拉伸区域，本地图上有效
 */
Widget loadImage({
  required String url,
  String assets = "assets",
  BoxFit fit = BoxFit.cover,
  String? package,
  Color? color,
  Widget? placeholder,
  Widget? error,
  Rect? centerSlice,
  Function(bool success)? onLoaded,
  FilterQuality filterQuality = FilterQuality.medium,
}) {
  if (strIsEmpty(url)) {
    return error ?? Container();
  }

  // 是网络图片
  if (url.startsWith("http")) {
    return CachedNetworkImage(
      imageUrl: url,
      fit: fit,
      color: color,
      placeholder: (context, url) {
        return placeholder ?? Container();
      },
      errorWidget: (context, url, err) {
        onLoaded?.call(false);
        return error ?? Container();
      },
      imageBuilder: onLoaded != null
          ? (context, imageProvider) {
              onLoaded.call(true);
              return Container(
                decoration: BoxDecoration(
                  image: DecorationImage(
                    image: imageProvider,
                    fit: fit,
                  ),
                ),
              );
            }
          : null,
    );
  }

  // 是项目assets图片
  if (url.startsWith(assets)) {
    return Image(
      image: AssetImage(url, package: package),
      fit: fit,
      color: color,
      filterQuality: FilterQuality.medium,
      centerSlice: centerSlice,
      errorBuilder: (context, err, stack) {
        return error ?? Container();
      },
    );
  }

  // 是本地沙盒图片
  return Image(
    image: FileImage(File(url)),
    fit: fit,
    color: color,
    filterQuality: filterQuality,
    centerSlice: centerSlice,
    errorBuilder: (context, err, stack) {
      return error ?? Container();
    },
  );
}

/// asset图片转ui.Image
/// import 'dart:ui' as ui;
Future<ui.Image> loadUiImage(String assetPath) async {
  final ByteData data = await rootBundle.load(assetPath);
  final Uint8List bytes = data.buffer.asUint8List();
  final ui.Codec codec = await ui.instantiateImageCodec(bytes);
  final ui.FrameInfo frameInfo = await codec.getNextFrame();
  final ui.Image image = frameInfo.image;
  return image;
}
